<?php
/**
 * User: huliangqing
 * Date :2020/8/17
 * Time :9:45
 */


namespace api\modules\v1\controllers;
use common\models\classify\Order;
use common\models\user\Member;
use oauth2\controllers\OnAuthController;

class WxappController extends OnAuthController
{
    public $modelClass = '';
    protected $authOptional = ['tixian','getsite','hu','qing'];

    public function actionTixian($money){
        $appid = "################";//商户账号appid
        $secret = "##########";//api密码
        $mch_id = "#######";//商户号
        $mch_no = "#######";
        $openid="123456789";//授权用户openid

        $arr = array();
        $arr['mch_appid'] = $appid;
        $arr['mchid'] = $mch_id;
        $arr['nonce_str'] = ugv::randomid(20);//随机字符串，不长于32位
        $arr['partner_trade_no'] = '1298016501' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000);//商户订单号
        $arr['openid'] = $openid;
        $arr['check_name'] = 'NO_CHECK';//是否验证用户真实姓名，这里不验证
        $arr['amount'] = $money;//付款金额，单位为分
        $desc = "###提现";
        $arr['desc'] = $desc;//描述信息
        $arr['spbill_create_ip'] = '192.168.0.1';//获取服务器的ip
        //封装的关于签名的算法
        $notify = new Notify_pub();
        $notify->weixin_app_config = array();
        $notify->weixin_app_config['KEY'] = $mch_no;

        $arr['sign'] = $notify->getSign($arr);//签名

        $var = $notify->arrayToXml($arr);
        $xml = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers', $var, 30, array(), 1);
        $rdata = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $return_code = (string)$rdata->return_code;
        $result_code = (string)$rdata->result_code;
        $return_code = trim(strtoupper($return_code));
        $result_code = trim(strtoupper($result_code));

        if ($return_code == 'SUCCESS' && $result_code == 'SUCCESS') {
            $isrr = array(
                'con'=>'ok',
                'error' => 0,
            );
        } else {
            $returnmsg = (string)$rdata->return_msg;
            $isrr = array(
                'error' => 1,
                'errmsg' => $returnmsg,
            );

        }
        return json_encode($isrr);
    }

   public function curl_post_ssl($url, $vars, $second = 30, $aHeader = array())
    {
        $isdir = "/cert/";//证书位置

        $ch = curl_init();//初始化curl

        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
        curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');//证书位置
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
        curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');//证书位置
        curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
        curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
        }
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);//全部数据使用HTTP协议中的"POST"操作来发送

        $data = curl_exec($ch);//执行回话
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }

    /**

     * 根据经纬度和半径计算出范围

     * @param string $lat 纬度

     * @param String $lng 经度

     * @param float $radius 半径

     * @return Array 范围数组

     */

    public function actionGetsite($lat, $lng, $radius) {

       // echo 111;die();
        $degree = (24901*1609)/360.0;
        $dpmLat = 1/$degree;
        $radiusLat = $dpmLat*$radius;
        $minLat = $lat - $radiusLat;    // 最小纬度
        $maxLat = $lat + $radiusLat;    // 最大纬度
        $mpdLng = $degree*cos($lat * (180));
        $dpmLng = 1 / $mpdLng;
        $radiusLng = $dpmLng*$radius;
        $minLng = $lng - $radiusLng;   // 最小经度
        $maxLng = $lng + $radiusLng;   // 最大经度
        /** 返回范围数组 */
        $scope = array(
            'minLat1'  => $minLat,
            'maxLat2'  => $maxLat,
            'minLng1'  => $minLng,
            'maxLng2'  => $maxLng,
        );
       // $a = self::actionHu($scope['minLat'],$scope['minLat'],$scope['minLng'],$scope['maxLng']);
        $data = Member::find()
            ->select('lng,lat,id,member_auth_state')
            ->asArray()
            ->all();
//        $arr =[];
//        foreach ($data as &$v){
//            $arr = $v;
//        }
       // dd($data);
        if($data){
          //var_dump(  $scope['minLat1']);die();
            $data = Member::find()
                ->select('lng,lat,id,member_auth_state')
                //->where(['member_auth_state'=>3])
                ->andwhere(['>','lng',$scope['minLng1']])
                ->andWhere(['<','lng',$scope['maxLng2']])
                ->andWhere(['>','lat',$scope['minLat1']])
                ->andWhere(['<','lat',$scope['maxLat2']])
                ->asArray()
                //->createCommand()->getSql();
                ->all();
            //dd($data);
           $a = array_column($data, 'id');
           $arr = Member::find()
               ->select('member_name,lng,lat,member_auth_state')
               ->where(['in','id',$a])
               ->andwhere(['member_auth_state'=>3])
               ->asArray()
               ->all();
            //dd($arr);

            //$status =[];
            foreach ($arr as $key=>$v){

                $status[$key]=$v;
                $status[$key]['distance']=number_format(self::actionHu($lng,$lat,$v['lng'],$v['lat']),'3').'米';

            }
        }
       return  $status;
    }
    /**
     * 计算二点之间距离
     * @param $lng1
     * @param $lat1
     * @param $lng2
     * @param $lat2
     * @return float|int
     */
    function actionHu($lng1, $lat1, $lng2, $lat2) {
        // 将角度转为狐度
        $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }

    public function actionQing(){
//
////        $myfile = fopen('2.html', "r") or die("Unable to open file!");
////        echo fread($myfile,filesize("webdictionary.txt"));
////        fclose($myfile);
//        //$handle = fopen("http://mp3.9ku.com/hot/2007/05-07/84566.mp3", "r");
//       // require '2.html';
//       // return $handle;
//        $a =[
//            'HU'=>'HULIANGQING'
//        ];
//        //var_dump(json_encode($a,true));die();
//        return json_encode($a,true);
        $data = Order::find()
            ->where(['news'=>1])
            ->select('id,news')
            ->asArray()
            ->count();
        // $arr = array_column($data,'id');
        //$a = Order::updateAll(['news'=>2],['in','id',$arr]);
        return $data;
    }



}